﻿using Kingdee.BOS.App.Data;
using Kingdee.BOS.Contracts;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.List;
using Kingdee.BOS.Core.List.PlugIn;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Core.Metadata.FormElement;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using System;
using System.ComponentModel;
using System.Linq;
using System.Runtime.InteropServices.ComTypes;
using System.Security.Cryptography;
using System.Text;

namespace PMAF.K3Cloud.SCM.BillList.BusinessPlugIn
{
    [HotUpdate]
    [Description("销售订单列表插件")]
    public class SaleOrderList:AbstractListPlugIn
    {
        public override void OnInitialize(InitializeEventArgs e)
        {
            base.OnInitialize(e);
        }
        public override void BarItemClick(BarItemClickEventArgs e)
        {
            base.BarItemClick(e);

            switch (e.BarItemKey.ToUpperInvariant())
            {
                //case "TBDELETE": 列表工具栏按钮事件，通过按钮Key[大写]来区分那个按钮事件
                //break;
                case "PMAF_UPDATEPURSNBTN":
                    //获取所有已选择行的数据
                    ListSelectedRowCollection selectedRows = ListView.SelectedRowsInfo;
                    StringBuilder messageStrs = new StringBuilder();
                    //获取行选择信息
                    var listDatas = ListModel.GetData(selectedRows);
                    foreach(var row in listDatas)
                    {
                        var billno = row["FBILLNO"];
                        var isShort = Convert.ToBoolean(row["F_PMAF_ISSHORT"]);
                        if (isShort == false)
                        {
                            string messageStr = string.Format("销售订单{0}不是空单，请选择空单更新流水号！", billno);
                            messageStrs.AppendLine(messageStr);
                        }
                    }
                    if (messageStrs.Length == 0)
                    {
                        int[] ids= new int[listDatas.Count];
                        int[] entryIds = new int[listDatas.Count];
                        int i = 0;
                        foreach ( var row in listDatas )
                        {
                            int id = Convert.ToInt32(row["FID"]);
                            int entryId = Convert.ToInt32(row["t2_FENTRYID"]);
                            ids[i] = id;
                            entryIds[i] = entryId;
                            i++;
                        }
                        //实例化动态表单
                        DynamicFormShowParameter formShowParameter
                            = new DynamicFormShowParameter
                            {
                                //调用哪个表单 PMAF_TEST
                                FormId = "PMAF_UpdatePurchaseSn"
                            };
                        //传递id、entryId
                        formShowParameter.CustomParams.Add("ids", GetIds(ids));
                        formShowParameter.CustomParams.Add("entryIds", GetIds(entryIds));
                        //加载动态表单
                        View.ShowForm(formShowParameter, delegate (FormResult result)
                        {
                            //定义接收值，并强制类型转换
                            DynamicObjectCollection returnData = (DynamicObjectCollection)result.ReturnData;
                            //如果值不为空，执行填充
                            if (returnData != null)
                            {
                                int[] billIds = new int[returnData.Count];
                                int itemIndex = 0;
                                foreach ( var item in returnData )
                                {
                                    billIds[itemIndex] = Convert.ToInt32(item["F_PMAF_FID"]);
                                }
                                OQLFilter salOrderFilter = new OQLFilter
                                {
                                    new OQLFilterHeadEntityItem() { FilterString = string.Format("FID IN {0}", GetIds(billIds)) }
                                };
                                DynamicObject[] salOrders = BusinessDataServiceHelper.Load(Context, "SAL_SaleOrder", null, salOrderFilter);
                                foreach ( var salOrder in salOrders)
                                {
                                    int billId = Convert.ToInt32(salOrder["Id"]);
                                    DynamicObjectCollection entry = (DynamicObjectCollection)salOrder["SaleOrderEntry"];
                                    int purchaseCount = 0;
                                    foreach( var item in entry)
                                    {
                                        int entryId = Convert.ToInt32(item["Id"]);
                                        foreach (var item1 in returnData)
                                        {
                                            int returnId = Convert.ToInt32(item1["F_PMAF_FID"]);
                                            int returnEntryId = Convert.ToInt32(item1["F_PMAF_FENTRYID"]);
                                            DynamicObject returnPurchase = (DynamicObject)item1["F_PMAF_PURCHASESN"];
                                            int returnPurchaseId = Convert.ToInt32(returnPurchase["Id"]);
                                            if (billId == returnId && entryId == returnEntryId)
                                            {
                                                item["F_PMAF_PurchaseSN_Id"] = returnPurchaseId;
                                            }
                                        }
                                        var purchase = Convert.ToInt32(item["F_PMAF_PurchaseSN_Id"]);
                                        if (purchase != 0)
                                        {
                                            purchaseCount++;
                                        }
                                    }
                                    if(purchaseCount == entry.Count)
                                    {
                                        salOrder["F_PMAF_ISSHORT"] = false;
                                    }
                                }
                                //构建销售订单元数据
                                IMetaDataService metaService = ServiceFactory.GetService<IMetaDataService>(Context);
                                FormMetadata purchaseSnMeta = (FormMetadata)metaService.Load(Context, "SAL_SaleOrder");
                                BusinessInfo businessInfo = purchaseSnMeta.BusinessInfo;
                                var operationNumber = "save";
                                DynamicObject[] dynamicObjects1 = BusinessDataServiceHelper.Save(Context, businessInfo, salOrders, operationNumber);
                            }
                        });
                    }
                    else
                    {
                        View.ShowWarnningMessage(messageStrs.ToString());
                        e.Cancel = true;
                    }
                    break;
                case "PMAF_EARNESTCALCULATEBTN":
                    //获取所有已选择行的数据
                    ListSelectedRowCollection eSelectedRows = ListView.SelectedRowsInfo;
                    //获取行选择信息
                    var eListDatas = ListModel.GetData(eSelectedRows);
                    if (eListDatas.Count <= 0)
                    {
                        View.ShowWarnningMessage("没有选择任何数据，请选择至少一行数据进行操作！");
                    }
                    else
                    {
                        //实例化动态表单
                        DynamicFormShowParameter formShowParameter
                            = new DynamicFormShowParameter
                            {
                                //调用哪个表单 PMAF_TEST
                                FormId = "PMAF_EarnestCalculate"
                            };
                        int[] ids = new int[eListDatas.Count];
                        int[] entryIds = new int[eListDatas.Count];
                        int i = 0;
                        foreach (var row in eListDatas)
                        {
                            int id = Convert.ToInt32(row["FID"]);
                            int entryId = Convert.ToInt32(row["t2_FENTRYID"]);
                            ids[i] = id;
                            entryIds[i] = entryId;
                            i++;
                        }
                        //传递id、entryId
                        formShowParameter.CustomParams.Add("ids", GetIds(ids));
                        formShowParameter.CustomParams.Add("entryids", GetIds(entryIds));
                        formShowParameter.OpenStyle.ShowType = ShowType.MainNewTabPage;
                        //加载动态表单
                        View.ShowForm(formShowParameter);
            }
                    break;
                case "PMAF_STOPBTN":
                    //获取所有已选择行的数据
                    ListSelectedRowCollection sSelectedRows = ListView.SelectedRowsInfo;
                    //获取行选择信息
                    var sListDatas = ListModel.GetData(sSelectedRows);
                    if (sListDatas.Count <= 0)
                    {
                        View.ShowWarnningMessage("没有选择任何数据，请选择至少一行数据进行操作！");
                    }
                    else
                    {
                        StringBuilder sm = new StringBuilder();
                        StringBuilder fm = new StringBuilder();
                        foreach (var row in sListDatas)
                        {
                            int id = Convert.ToInt32(row["FID"]);
                            string billNo = row["FBillNo"].ToString();
                            DynamicObject[] saleOrders = GetSaleOrder(id);
                            string stopStatus = saleOrders[0]["F_PMAF_StopStatus_H"].ToString();
                            if (stopStatus == "A")
                            {
                                string sqlStr = string.Format(@"/*dialect*/
                                        UPDATE T_SAL_ORDER SET F_PMAF_STOPSTATUS_H='B' WHERE FID={0};
                                        ", id);
                                int result = DBUtils.Execute(Context, sqlStr);
                                sm.Append(string.Format("单据{0}终止成功。", billNo));
                            }
                            else
                            {
                                fm.Append(string.Format("单据{0}已经终止，无需再次执行终止！", billNo));
                            }
                        }
                        View.ShowMessage(sm.ToString()+fm.ToString());
                    }
                    break;
                default:
                    break;
            }
        }

        /// <summary>
        /// 把int数组转化为SQL语句的IN后面括号部分 PMAF_EarnestCalculateBtn
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        private string GetIds(int[] ids)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("(");
            int i = 0;
            foreach ( var id in ids )
            {
                sb.Append(id.ToString());
                if ( i < ids.Length - 1 )
                {
                    sb.Append(", ");
                }
                i++;
            }
            sb.Append(")");
            return sb.ToString();
        }

        private DynamicObject[] GetSaleOrder(int id)
        {
            //销售订单过滤条件
            OQLFilter saleOrderFilter = new OQLFilter
            {
                new OQLFilterHeadEntityItem() { FilterString = string.Format("FID='{0}'", id) }
            };
            //查询销售订单
            DynamicObject[] saleOrders = BusinessDataServiceHelper.Load(Context, "SAL_SaleOrder", null, saleOrderFilter);
            return saleOrders;
        }
    }
}
